<?php
namespace plugin\admin\app\common\service;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class jdApi
{
    /**
     * 上品接口
     * @throws GuzzleException
     */
    public static function goodsInsert($goodsInfo, $spuData, $shopInfo, $add_type): array
    {
        // 1. 处理数据
        $caiJiRes = $goodsInfo['item'];
        $jdSaveData['title'] = (new jdApi)->str_operation(50, $caiJiRes['title']);
        // 2. 店内分类
        $jdSaveData['shopCategories'] = $spuData['shopCategoryId'];
        // 3. 根据商品名称获取品牌和分类id
        $getSkuCateBrandBySkuName_res = self::getCategoryId($caiJiRes['title'], $shopInfo);
        $jdSaveData['brandId'] = $getSkuCateBrandBySkuName_res['data']['brandId'];
        $jdSaveData['categoryId'] = $getSkuCateBrandBySkuName_res['data']['categoryId'];
        $imageContent = "";
        foreach ($caiJiRes['desc_img'] as $value) {
            $imageContent .= '<img src="'.$value.'" alt="">';
        }
        $jdSaveData['notes'] = '<p>' .$imageContent. '</p>';
        // 5. 商品价格
        $jdSaveData['jdPrice'] = number_format($caiJiRes['price'] + $caiJiRes['price'] * ($spuData['price_config'] / 100), 2, '.', ''); // 价格
        // 6. 上品
        $newImages = [];
        foreach ($caiJiRes['item_imgs'] as $k => $v){
            // 京东到家要求主图<=6张，我们这里留下来7张，然后再删除第一张主图【$k <=6 其实就是留下来了7张】
            if($k <= 6) {
                $newImages[$k] = "https://" . substr($v['url'], 2);
            }
        }
        // 删除第一张主图
        array_shift($newImages);
        // 店内分类
        $shopCategories_arr = explode(',', $jdSaveData['shopCategories']);
        $appConfig = [
            'app_key'    => $spuData['shopInfo']['app_key'],
            'app_secret' => $spuData['shopInfo']['app_secret'],
            'app_token'  => $spuData['shopInfo']['token']
        ];
        if($add_type == 2 && $caiJiRes['sku_list'] != '') {
            $app_param = [
                'outSuperId'       => (string)$caiJiRes['num_iid'],
                'shopCategories' => end($shopCategories_arr),
                "categoryId"     => $jdSaveData['categoryId'],
                "brandId"        => $jdSaveData['brandId'],
                "superName"        => $jdSaveData['title'],
                "skuPrice"       => intval(round($jdSaveData['jdPrice']) * 100),
                "weight"         => 1,
                "images"         => $newImages,
                "productDesc"    => substr($jdSaveData['notes'], 0, 1800),
                "fixedStatus"    => 1,
                "ifViewDesc"     => 0,
                "isSale"         => true,
                "sellCities"     => 0,
            ];
            $goodsInsertTwo_res = (new jdApi)->goodsInsertTwo($caiJiRes, $spuData);
            $app_param = array_merge($goodsInsertTwo_res, $app_param);
            $url = 'https://openapi.jddj.com/djapi/pms/addSpu';
        } else {
            $app_param = [
                'traceId'        => md5("goodsSaveInterface" . rand(999, 12318)),
                'outSkuId'       => (string)$caiJiRes['num_iid'],
                'shopCategories' => end($shopCategories_arr),
                "categoryId"     => $jdSaveData['categoryId'],
                "brandId"        => $jdSaveData['brandId'],
                "skuName"        => $jdSaveData['title'],
                "skuPrice"       => intval(round($jdSaveData['jdPrice']) * 100),
                "weight"         => 1,
                "images"         => $newImages,
                "productDesc"    => substr($jdSaveData['notes'], 0, 1800),
                "fixedStatus"    => 1,
                "ifViewDesc"     => 0,
                "isSale"         => true,
                "upc"            => "450618536536"
            ];
            $url = 'https://openapi.jddj.com/djapi/pms/addSku';
        }
        $paramRes = self::paramOperationPost($appConfig, $app_param);
        $sendRequest = new sendRequest();
        $response = $sendRequest->jdRequestPost($url, $paramRes);
        if($response['status_code'] == 200 && ($response['body']['code'] == 0 && $response['body']['success'] == 1)) {
            $res_data = json_decode($response['body']['data'], true);
            if(isset($res_data['result']['resultCode'])) {
                switch ($res_data['result']['resultCode']) {
                    case 1100001:
                        $returnData['code'] = 1;
                        $returnData['status'] = true;
                        $returnData['statusCode'] = 1020;
                        break;
                    case 1009001 || 11001:
                        $returnData['code'] = 0; // 失败，已经存在
                        $returnData['status'] = false;
                        $returnData['statusCode'] = 1021;
                        break;
                    default:
                        $returnData['code'] = 0; // 执行失败
                        $returnData['status'] = false;
                        $returnData['statusCode'] = 1022;
                        break;
                }
                $returnData['msg'] = $res_data['result']['failedDetail'];
            } else {
                switch ($res_data['code']) {
                    case 0:
                        $returnData['code'] = 1;
                        $returnData['status'] = true;
                        $returnData['statusCode'] = 1020;
                        break;
                    case 31010:
                        $returnData['code'] = 0; // 失败，已经存在
                        $returnData['status'] = false;
                        $returnData['statusCode'] = 1021;
                        break;
                    default:
                        $returnData['code'] = 0; // 执行失败
                        $returnData['status'] = false;
                        $returnData['statusCode'] = 1022;
                        break;
                }
                $returnData['msg'] = $res_data['msg'];
            }
            return $returnData;
        } else {
            return [
                'code'       => 0,
                'msg'        => "上传到家执行失败",
                'status'     => false,
                'statusCode' => 1022
            ];
        }
    }

    /**
     * 处理字符串获取相应长度
     * @param $length
     * @param $str
     * @return string
     */
    public function str_operation($length, $str): string
    {
        $byteCount = preg_replace('/[^\p{Han}\p{Latin}0-9]/u', '', $str);
        return mb_substr($byteCount, 0, $length, 'UTF-8');
    }

    public function goodsInsertTwo($caiJiRes, $spuData): array
    {
        $app_param = [];
        // 1. 获取有几个销售属性
        $props_arr = [];
        foreach ($caiJiRes['props_list'] as $key => $value) {
            if($key == 2) {
                break;
            }
            if (strpos($key, '0:') !== false) {
                if ($key == "0:0") {
                    $props_arr['props_a']['saleAttrName'] = explode(':', $value)[0];
                }
                $val = explode($props_arr['props_a']['saleAttrName'] . ':', $value)[1];
                $props_arr['props_a']['saleAttrValueNameList'][] = (new jdApi)->str_operation(30, $val);
            } else if(strpos($key, '1:') !== false) {
                if ($key == "1:0") {
                    $props_arr['props_b']['saleAttrName'] = explode(':', $value)[0];
                }
                $val = explode($props_arr['props_b']['saleAttrName'] . ':', $value)[1];
                $props_arr['props_b']['saleAttrValueNameList'][] = (new jdApi)->str_operation(30, $val);
            }
        }
        if (isset($props_arr['props_b'])) {
            $app_param['saleAttrRelationInfoList'][] = $props_arr['props_b'];
        }
        if (isset($props_arr['props_a'])) {
            $app_param['saleAttrRelationInfoList'][] = $props_arr['props_a'];
        }
        // 2. sku的详细信息 skuMainInfo
        $skuMainInfo = [];
        foreach ($caiJiRes['sku_list'] as $key => $value) {
            $name_arr          = explode(':', $value['properties_name']);
            $sku_price = number_format($value['price'] + $value['price'] * ($spuData['price_config'] / 100), 2, '.', ''); // 价格
            $skuMainInfo[$key] = [
                'skuName'     => end($name_arr),
                'outSkuId'    => (string)$value['sku_id'],
                'fixedStatus' => 1,
                'images'      => "https:" . str_replace("n9/s40x40_jfs", "n12/jfs", $caiJiRes['props_img'][$value['properties']]),
                'skuPrice'    => intval(round($sku_price) * 100),
                'weight'      => 1,
                'isSale'      => true
            ];
            if(count($app_param['saleAttrRelationInfoList']) == 2) {
                $skuMainInfo[$key]['saleAttrValues'][] = [
                    'saleAttrName' => $props_arr['props_b']['saleAttrName'],
                    'saleAttrValueName' => (new jdApi)->str_operation(30, end($name_arr))
                ];
            }
            $sku_val = explode(';', $name_arr[3])[0];
            $skuMainInfo[$key]['saleAttrValues'][] = [
                'saleAttrName' =>  $props_arr['props_a']['saleAttrName'],
                'saleAttrValueName' => (new jdApi)->str_operation(30, $sku_val)
            ];
        }
        $app_param['skuMainInfo'] = $skuMainInfo;
        return $app_param;
    }

    /**
     * 查询商家店内分类信息接口
     * 首页>常规接口> 查询商家店内分类信息接口
     * @throws GuzzleException
     */
    public static function queryCategoriesByOrgCode($shopInfo)
    {
        $app_param = ['fields'=>'ID,PID,SHOP_CATEGORY_NAME,SORT'];
        $url = 'https://openapi.jddj.com/djapi/pms/queryCategoriesByOrgCode';
        $appConfig = [
            'app_key'    => $shopInfo->app_key,
            'app_secret' => $shopInfo->app_secret,
            'app_token'  => $shopInfo->token
        ];
        $paramRes = self::paramOperation($appConfig, $app_param);
        $sendRequest = new sendRequest();
        $response = $sendRequest->jdRequest($url.$paramRes);
        if($response['status_code'] == 200 && $response['body']['code'] == 0) {
            $categoryData = json_decode($response['body']['data'], true);
            $menus_parent = toLabel('pid', 0, $categoryData['result']);
            $data = [];
            foreach ($menus_parent as $key => $value) {
                $data[$key] = $value;
                if(count(toLabel('pid', $value['value'], $categoryData['result'])) > 0) {
                    $data[$key]['children'] = toLabel('pid', $value['value'], $categoryData['result']);
                    foreach ($data[$key]['children'] as $k => $val) {
                        if(count(toLabel('pid', $val['value'], $categoryData['result'])) > 0) {
                            $data[$key]['children'][$k]['children'] = toLabel('pid', $val['value'], $categoryData['result']);
                        }
                    }
                }
            }
            return $data;
        } else {
            return false;
        }
    }

    public static $UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36';
    public static $baseUrl = 'https://sff.jddj.com/';
    public static $cookies = 'mba_muid=169461004665658869907; store_deviceid=6814b2efba310cef4eeeea9816696039; shshshfpx=0d082d5b-fd75-18e3-179b-37295754313e-1680167016; flash=2_B7myjeQUdE1ujvgwdcEARTscDM_DbPYzY-PmFG6ePaXxPh1U97xu9KLb9rrbbuyEYfCUASvc8ZoQf9G60B9WtQx2wtkdzjaUc9ENCAbl6pV*; thor=479F638125D75466334F74F2E4C1D8F55D2A88867A0561813B22D056887A885C756762BB38697D2BA1DEF14BD7B6DA5ADAD8B80D594BBF9284DD000E76F15A579A4EECE986B154FE0BD34BFCDD98182672E6A5CFDD8D259649FA478FD1E4A68B874ED9B1FE811E618F743F96D62324E1BE98ECBBBFD9C141EF1BF50EEF806B22B3DDA363EB4B41F39B27220ADF9DD9AE; pin=JDJDJDJD535; unick=u_ijgd89s7vzcg; __jda=157302241.169461004665658869907.1694610046.1695880460.1698043360.15; __jdv=157302241%7Cdirect%7C-%7Cnone%7C-%7C1698043360660; __jdc=157302241; deviceid_pdj_jd=H5_DEV_9C65A37C-7AFF-478C-8B29-2D355190EF04; client_id=dcc7aa87-790c-4e6b-8a6d-7896f4b52eee; 3AB9D23F7A4B3C9B=H67SA7MYCWR7GEUISJ25RZJZ6GFKPGGENTST62VJSG7WDIMV32VVW7B3Q5HHSXQ45TO46KC56YCTXGH6VQMMW42TGE; lsp-store1.jd.local=IVEONBO5A67I7L2GGQIPETM6THF4IHDFOK2JSTO6XPBGTJ6AHJW6TS47PGSNLMJNJFOW4FWXF6W3EMLR67IJKUO5OJX5K3UTHMFXWDLZ43EXULSJCM34B7IS5YFICBSUXOT6KD7HRFZHQNZSVMJCHM73G3MSRRBLOADIU6WLAFEZTLRFXCMMERTNWRKKGYKWVBCMQMFW3MHLYAG2N6BW3MZPE7QSNRL3AGPS4RWUXK2GZ5OKNLKI5CF3LZOHX44EGQ5CMB2LGS2QITC5N22PCXD4WP7YT6C3FHPYOLC2P3NAEVF3LN2SGAH3CFJNL7P5HW6DXPKDEI7NXZHFPU4OX7DWNAZ4RJJFCOIIYCNGA3XDTEDPVG735W5USLH5MCUKBI5NXUR7JGNR3RVPRB5FUGCDG5TNXV43PLLWTJ2XNQHLCHIN43EQ; user_email=xinnuo003; user_key=794645; vender_id=382284; vender_name=\u946B\u8BFA\u5BB6\u7535\u7EFC\u5408\u5356\u573A; privige-eid=H67SA7MYCWR7GEUISJ25RZJZ6GFKPGGENTST62VJSG7WDIMV32VVW7B3Q5HHSXQ45TO46KC56YCTXGH6VQMMW42TGE; __jdb=157302241.2.169461004665658869907|15.1698043360; lsp-store1.jddj.com=IVEONBO5A67I7L2GGQIPETM6THF4IHDFOK2JSTO6XPBGTJ6AHJW6TS47PGSNLMJNJFOW4FWXF6W3EMLR67IJKUO5OJX5K3UTHMFXWDLZ43EXULSJCM34B7IS5YFICBSUXOT6KD7HRFZHQNZSVMJCHM73G3MSRRBLOADIU6WLAFEZTLRFXCMMERTNWRKKGYKWVBCMQMFW3MHLYAG2N6BW3MZPE7QSNRL3AGPS4RWUXK2GZ5OKNLKI5CF3LZOHX44ELODDJWEHQXVMJCC3436EO67NNGWNINY5QV6PO3YUHHUYHOZCUANFL2NRNVV2DQ7RDYDEEXVFMFEYX76C6XG6AUVVJQXD5XHGDK4FVJDZUAIXUZAYZSXRPX2CDILM3N4KJDTHS725J6JUALAJMUVJWPWUWA; josl-privilege1.jddj.com=IVEONBO5A67I7L2GGQIPETM6THF4IHDFOK2JSTO6X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uzzleException
     */
    public static function getCategoryId($title, $shopInfo)
    {
//        try {
//            $client = new Client();
//            $headers = [
//                'User-Agent' => self::$UserAgent,
//                'Cookie'     => self::$cookies,
//                'Referer'    => 'https://store.jddj.com/',
//                'Origin'     => 'https://store.jddj.com'
//            ];
//            $formData = [
//                'v'     => '1.0',
//                'appId' => 'YNE4XWZFDHXOYGKZU5FN',
//                'api'   => 'dsm.pms.web.merchantCategory.pms.getCategoryRecommend',
//                'body'  => '{"firstCategoryId":0,"secondCategoryId":0,"categoryId":0,"skuName":"' . $title . '","brandId":""}'
//            ];
//            $response = $client->request('POST', self::$baseUrl, ['headers'=>$headers, 'form_params'=>$formData]);
//            $response = $response->getBody()->getContents();
//            $res = json_decode($response);
//            return [
//                'data' => [
//                    'brandId' => $res->result->brandIds[0],
//                    'categoryId' => json_decode($res->result->categoryIds[0])[2]
//                ]
//            ];
//        }catch (Exception $e){
//            //没有推荐分类需要返回message，否则会影响断点续传
//            return false;
//        }
        $app_param = [
            'productName' => $title,
            'fields' => 'brand,category'
        ];
        $url = 'https://openapi.jddj.com/djapi/pms/getSkuCateBrandBySkuName';
        $appConfig = [
            'app_key'    => $shopInfo['app_key'],
            'app_secret' => $shopInfo['app_secret'],
            'app_token'  => $shopInfo['token']
        ];
        $paramRes = self::paramOperation($appConfig, $app_param);
        $sendRequest = new sendRequest();
        $response = $sendRequest->jdRequest($url.$paramRes);
        if($response['status_code'] == 200 && $response['body']['code'] == 0) {
            $categoryData = json_decode($response['body']['data'], true);
            return [
                'data' => [
                    'brandId' => $categoryData['result']['brandId'],
                    'categoryId' => $categoryData['result']['categoryId']
                ]
            ];
        } else {
            return false;
        }
    }

    // 京东到家参数处理
    public static function paramOperation($appConfig, $param): string
    {
        $api_level_param = [
            "app_key"       => $appConfig['app_key'],
            "format"        => "json",
            "jd_param_json" => json_encode($param, JSON_UNESCAPED_UNICODE),
            "timestamp"     => date('Y-m-d H:i:s'),
            "token"         => $appConfig['app_token'],
            "v"             => "1.0"
        ];
        ksort($api_level_param);
        $sortedString = $appConfig['app_secret'];
        foreach ($api_level_param as $k=>$v){
            $v = (string)$v;
            if("sign" !== $k)
            {
                $sortedString .= "$k$v";
            }
        }
        $sortedString .= $appConfig['app_secret'];
        $sign = strtoupper(md5($sortedString));
        $api_level_param['sign'] = $sign;
        $api_level_param['jd_param_json'] = urlencode($api_level_param['jd_param_json']);
        $urlParam = "?";
        foreach ($api_level_param as $k=>$v){
            if ($urlParam == "?"){
                $urlParam .= "{$k}={$v}";
            }else{
                $urlParam .= "&{$k}={$v}";
            }
        }
        return $urlParam;
    }

    // 京东到家参数处理POST
    public static function paramOperationPost($appConfig, $param): array
    {
        $api_level_param = [
            "app_key"       => $appConfig['app_key'],
            "format"        => "json",
            "jd_param_json" => json_encode($param, JSON_UNESCAPED_UNICODE),
            "timestamp"     => date('Y-m-d H:i:s'),
            "token"         => $appConfig['app_token'],
            "v"             => "2.0"
        ];
        ksort($api_level_param);
        $sortedString = $appConfig['app_secret'];
        foreach ($api_level_param as $k=>$v){
            $v = (string)$v;
            if("sign" !== $k)
            {
                $sortedString .= "$k$v";
            }
        }
        $sortedString .= $appConfig['app_secret'];
        $sign = strtoupper(md5($sortedString));
        $api_level_param['sign'] = $sign;
        //$api_level_param['jd_param_json'] = urlencode($api_level_param['jd_param_json']);
        return $api_level_param;
    }
}